package 中国.杨森.实验室.jpa.sqlserver;

import java.time.LocalDateTime;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class 单个
{
	@Test
	public void 查()
	{
		过车记录 o = em.find(过车记录.class, "{A62CC3AC-0B85-4CE0-917B-25B6963FAAA4}");
		if (o == null)
		{
			throw new NullPointerException();
		}
		System.out.println(o.get时间());
	}

	@Test
	public void 带条件()
	{
		LocalDateTime time = LocalDateTime.now();
		time = time.minusMinutes(30);
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<过车记录> cq = cb.createQuery(过车记录.class);
		Root<过车记录> root = cq.from(过车记录.class);
		cq.select(root);
		Predicate p = cb.greaterThan(root.get(过车记录_.时间), time);
		cq.where(p);
		cq.orderBy(cb.desc(root.get(过车记录_.时间)));
		TypedQuery<过车记录> t = em.createQuery(cq);
		t.setMaxResults(10);
		t.setFirstResult(0);
		List<过车记录> list = t.getResultList();
		if (list.size() > 0)
		{
			System.out.println(list.size());
			for (int i = 0; i < list.size(); i++)
			{
				System.out.println(list.get(i).toString());
			}
		}
	}

	EntityManagerFactory emf;
	EntityManager em;

	@Before
	public void 启动()
	{
		emf = Persistence.createEntityManagerFactory("sqlserver");
		em = emf.createEntityManager();
		em.getTransaction().begin();
	}

	@After
	public void 关闭()
	{
		em.getTransaction().commit();
		em.close();
		emf.close();
	}
}
